package pbl;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @author AMPM
 * 
 * This class is instantiated and set to run in an individual
 * thread by the Simple TCP Server to handle the activities
 * involved in serving a client.
 *
 */

public class ClientHandler implements Runnable {
	private Socket socket;
	
	public ClientHandler(Socket socket) {
		this.socket = socket;
	}
	
	public void run()  {
		try {
			String result;
		
			// get the input and output stream from the socket
			InputStream is = socket.getInputStream();
			OutputStream os = socket.getOutputStream();
			
			// wrap them in the ObjectInputStream and ObjectOutputStream objects
			ObjectOutputStream oos = new ObjectOutputStream( os );
			ObjectInputStream ois = new ObjectInputStream(is);
	    
			// get the data transmitted from the client
			Boolean toUpperCase = (Boolean) ois.readObject();
			String message = (String) ois.readObject();
	    
			// the string transmitted is converted to upper or lower
			// case depending on the transmitted boolean value
			if (toUpperCase)
			{
				result = message.toUpperCase();
			}
			else
			{
				result = message.toLowerCase();
			}
			
			// the result is written to the ObjectOutputStream and flushed
			oos.writeObject( result );
			oos.flush();
			
			socket.close();
		}
		catch (IOException ignore) {}
		catch (ClassNotFoundException ignore) {}
	}
}

